package com.ofhb.webapp.client.ui.grid;

import java.util.ArrayList;
import java.util.List;

public class GridData {
	private List<GridHeaderCell> gridHeaderRow = new ArrayList<GridHeaderCell>();
	private List<ArrayList<String>> gridRows = new ArrayList<ArrayList<String>>();
	
	public void addRow(ArrayList<String> gridRow) {
		getGridRows().add(gridRow);
	}

	public void addColumn(String columnName, int length, GridDataType type) {
		GridHeaderCell gridHeaderCell = new GridHeaderCell(columnName, length, type);
		getGridHeaderRow().add(gridHeaderCell);
	}
	public void setHeaderRows(List<GridHeaderCell> headerRow) {
		gridHeaderRow.clear();
		gridHeaderRow.addAll(headerRow);
	}
	
	public void setRows(List<ArrayList<String>> dataRows) {
		gridRows.clear();
		gridRows.addAll(dataRows);
	}

	public void sort(int index, String sort) {
		index = index + 1;
		int len = getGridRows().size();
		boolean swapped = true;
		int j = 0;
		ArrayList<String> tmp;
		while (swapped) {
			swapped = false;
			j++;
			for (int i = 0; i < len - j; i++) {
				
				GridDataType type = gridHeaderRow.get(index).getType();

				if (type == GridDataType.TEXT) {
					String str1 = getGridRows().get(i).get(index);
					String str2 = getGridRows().get(i + 1).get(index);
					
					if(sort.equalsIgnoreCase("asc")) {
						if (str1.compareTo(str2) > 0) {
							tmp = getGridRows().get(i);
							getGridRows().set(i, getGridRows().get(i + 1));
							getGridRows().set(i + 1, tmp);
							swapped = true;
						}
					} else {
						if (str1.compareTo(str2) < 0) {
							tmp = getGridRows().get(i);
							getGridRows().set(i, getGridRows().get(i + 1));
							getGridRows().set(i + 1, tmp);
							swapped = true;
						}
					}
					
				} else if (type == GridDataType.NUMBER) {
					double n1 = Double.parseDouble(getGridRows().get(i).get(index));
					double n2 = Double.parseDouble(getGridRows().get(i + 1).get(index));
					if(sort.equalsIgnoreCase("asc")) {
						if (n1 > n2) {
							tmp = getGridRows().get(i);
							getGridRows().set(i, getGridRows().get(i + 1));
							getGridRows().set(i + 1, tmp);
							swapped = true;
						}
					} else {
						if (n1 < n2) {
							tmp = getGridRows().get(i);
							getGridRows().set(i, getGridRows().get(i + 1));
							getGridRows().set(i + 1, tmp);
							swapped = true;
						}
					}
					
					
				}
			}
		}
	}
	
	public List<GridHeaderCell> getGridHeaderRow() {
		return gridHeaderRow;
	}

	public List<ArrayList<String>> getGridRows() {
		return gridRows;
	}
	
}
